import { login, autoLogin, logout, getInfo, refreshtoken, newLogin, doQueryFlowStatus } from '@/api/user'
import { getToken, getNewToken, setToken, setNewToken, removeToken, removeNewToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  newToken: getNewToken(),
  newUserInfo: {},
  name: '',
  workNo: '',
  deptName: '',
  avatar: '',
  introduction: '',
  roles: [],
  menuList: [],
  permissions: [],
  permisaction: [],
  circulationStatus: [] // 审批流程
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NEW_TOKEN: (state, token) => {
    state.newToken = token
  },
  SET_NEW_USER_INFO: (state, info) => {
    state.newUserInfo = info
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_LASTPWDDAYS: (state, lastPwdDays) => {
    state.lastPwdDays = lastPwdDays
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_WORKNO: (state, workNo) => {
    state.workNo = workNo
  },
  SET_DEPTNAME: (state, deptName) => {
    state.deptName = deptName
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_AVATAR: (state, avatar) => {
    if (avatar.indexOf('http') !== -1) {
      state.avatar = avatar
    } else if (avatar == '') {
      state.avatar = ''
    } else {
      state.avatar = process.env.VUE_APP_BASE_API + avatar
    }
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_MENU_LIST: (state, menuList) => {
    state.menuList = menuList
  },
  SET_PERMISSIONS: (state, permisaction) => {
    state.permisaction = permisaction
  },
  SET_CIRCULATIONSTATUS: (state, circulationStatus) => {
    state.circulationStatus = circulationStatus
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo)
        .then(response => {
          const { token } = response
          commit('SET_TOKEN', token)
          setToken(token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  newLogin({ commit, dispatch }, userInfo) {
    /* {data:{metdata:{},param:{phoneNumber:'18121298510',
      code:'666666'},sign:"111111"}}*/

    return new Promise((resolve, reject) => {
      const mockData = { 'data': { 'metdata': { 'version': 'V2.0', 'model_code': 'HRAILOGIN/LOGIN', 'user': '7414ce02dd05476cbdab0a8345493017', 'timestamp': 1565609622824, 'req_src': 'HRAI', 'ip_address': '112.22.186.74', 'address': '江苏省苏州市', 'custId': '000000000000410', 'func_code': 'STAFF_MANAGEMENT' }, 'param': userInfo, 'sign': '' }}
      newLogin(mockData)
        .then(response => {
          console.log(2323, response)
          const { records } = response
          const token = records[0].token
          commit('SET_NEW_TOKEN', token)
          commit('SET_NEW_USER_INFO', records[0])
          setNewToken(token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取流程状态
  getCirculationStatus({ commit }) {
    return new Promise((resolve, reject) => {
      const params = { 'data': { 'metdata': {}, 'param': { 'paramName': window.$config.folderName }, 'sign': '111111' }}
      doQueryFlowStatus(params).then(res => {
        const obj = res.records[0]
        const data = obj.flowStatus.map(item => {
          return { label: item.name, value: item.key }
        })
        commit('SET_CIRCULATIONSTATUS', data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  autoLogin({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      autoLogin(userInfo)
        .then(response => {
          const { token } = response
          commit('SET_TOKEN', token)
          setToken(token)
          router.push({ path: '/baqsj/report' })
          resolve()
        })
        .catch(error => {
          router.push({ path: '/' })
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        if (!response || !response.records.length) {
          commit('SET_TOKEN', '')
          commit('SET_NEW_TOKEN', '')
          removeToken()
          removeNewToken()
          resolve()
        }
        const data = response.records[0]
        const {
          // userId,
          roles,
          menuList,
          username,
          // workNo,
          // avatar,
          // introduction,
          permissions
          // lastPwdDays,
          // deptName
        } = data
        // console.log(response.data)
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_PERMISSIONS', permissions)
        // commit('SET_LASTPWDDAYS', lastPwdDays)
        commit('SET_ROLES', roles)
        commit('SET_NAME', username)
        commit('SET_MENU_LIST', menuList)
        // commit('SET_DEPTNAME', deptName)
        // commit('SET_WORKNO', workNo)
        // commit('SET_USERID', userId)
        // commit('SET_AVATAR', avatar)
        // commit('SET_INTRODUCTION', introduction)
        resolve(data)
      })
        .catch(() => {
          commit('SET_TOKEN', '')
          commit('SET_NEW_TOKEN', '')
          setToken('')
          setNewToken('')
          router.push({ path: '/' })
        })
    })
  },
  // 退出系统
  LogOut({ commit, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_NEW_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_PERMISSIONS', [])
      removeToken()
      removeNewToken()
      resolve()
      /* logout(state.token)
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_NEW_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          removeNewToken()
          resolve()
        })
        .catch(error => {
          reject(error)
        })*/
    })
  },
  // 刷新token
  refreshToken({ commit, state }) {
    return new Promise((resolve, reject) => {
      refreshtoken({ token: state.token })
        .then(response => {
          const { token } = response
          commit('SET_TOKEN', token)
          setToken(token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, {
        root: true
      })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
